package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.admin.NewsAutoScanConstants;
import com.heima.model.common.constants.admin.NewsUpOrDownConstants;
import com.heima.model.common.constants.admin.PublishArticleConstants;
import com.heima.model.common.constants.admin.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.config.RabbitConfig;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //校验参数
        //校验分页
        dto.checkParam();
        //校验登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "需要登录才能操作");
        }
        //校验文章标题
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.<WmNews>lambdaQuery();
        queryWrapper.like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
        //校验频道
        queryWrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //文章状态
        queryWrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //时间
        queryWrapper.between(dto.getBeginPubDate() != null && dto.getEndPubDate() != null, WmNews::getCreatedTime, dto.getBeginPubDate(), dto.getEndPubDate());
        //用户id查询
        queryWrapper.eq(WmNews::getUserId, user.getId());
        //时间降序
        queryWrapper.orderByDesc(WmNews::getCreatedTime);
        //分页查询
        Page<WmNews> wmNewsPage = new Page<>(dto.getPage(), dto.getSize());
        //条件查询
        IPage<WmNews> page = page(wmNewsPage, queryWrapper);
        //返回查询封装结果
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
        //设置host
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 自媒体文章-发布、修改、保存草稿
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        //1.校验参数
        WmNews wmNews = parseDtoToWmNews(dto);

        //2保存修改文章
        saveOrUpdateWmNews(wmNews);

        //3.设置内容和封面与素材的关联关系
        //提取出内容中，所涉及的素材路径
        List<String> imagesUrl = parseContentImages(wmNews.getContent());

        //保存文章内容引用素材的关联关系
        saveRelativeInfo(imagesUrl, wmNews, WemediaConstants.WM_CONTENT_REFERENCE);

        //保存封面图片与素材关联关系
        saveRelativeInfoForCover(imagesUrl, wmNews, dto);
        //TODO 发送mq消息 触发自动审核
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
        log.info("成功发送文章自动审核消息 ==> 队列:{}, 文章id:{}", NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    /**
     * 根据id删除文章
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult deleteById(Integer id) {
        //校验参数
        //id
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "id不能为空");
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "数据为空");
        }
        //判断status（关联）的值是否为9，enable（下架）是否为1
        if (WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus()) && WemediaConstants.WM_NEWS_UP.equals(wmNews.getEnable())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "数据已发布，不允许删除");
        }
        //去除素材与文章关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        //执行删除
        removeById(wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //校验参数
        //id ,dto
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "数据不能为空");
        }
        //上下架状态
        if (dto.getEnable() == null && !WemediaConstants.WM_NEWS_UP.equals(dto.getEnable()) && !WemediaConstants.WM_NEWS_DOWN.equals(dto.getEnable())) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR, "上下架状态异常");
        }
        //根据id获得文章消息
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //审核状态
        if (!WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章不是发布状态，不能上下架");
        }
        //修改文章状态
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId()).set(WmNews::getEnable, dto.getEnable()));
        //5. 上下架发送消息通知  用于同步article 及 elasticsearch
        if (wmNews.getArticleId()!=null) {
            if(wmNews.getStatus().equals(WemediaConstants.WM_NEWS_UP)){
                // 上架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
            }else {
                // 下架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,wmNews.getArticleId());
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        Integer currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        //校验Title是否有值
        if(StringUtils.isNotBlank(dto.getTitle())){
            //不为空，加上条件
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        //2.分页查询
        List<WmNewsVO> listAndPage = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long listCount = wmNewsMapper.findListCount(dto);
        //3.结果返回
        PageResponseResult result = new PageResponseResult(currentPage, dto.getSize(), listCount, listAndPage);
        //设置host
        result.setHost(webSite);
        return result;
    }

    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findOneVo(Integer id) {
        //1.校验参数
        if(id == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"参数不能为空");
        }
        //按条件查询
        WmNewsVO wmNewsVO= wmNewsMapper.findByIdWmNews(id);
        //3.封装结果
        ResponseResult result = ResponseResult.okResult(wmNewsVO);
        //4.设置host
        result.setHost(webSite);
        return result;
    }

    /**
     * 自媒体文章人工审核
     * @param status  2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if(dto==null||dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"数据或者id为空");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"数据不存在");
        }
        // 检查文章状态 不能为9  已发布
        if(WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        //判断msg是否为空，不为空修改
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        //执行修改
        this.updateById(wmNews);
        // TODO 通知定时发布文章
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面图片与素材关联关系
     *
     * @param imagesUrl
     * @param wmNews
     * @param dto
     */
    private void saveRelativeInfoForCover(List<String> imagesUrl, WmNews wmNews, WmNewsDTO dto) {
        //判断前端传入的type参数是否为-1
        List<String> images = dto.getImages();
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            //自动生成封面
            //获得图片参数
            int size = imagesUrl.size();
            //判断个数
            if (size == 0) {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            } else if (size <= 2) {
                //有图(单图)
                //用流的方式获取图片
                images = imagesUrl.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else {
                //多图（三张）
                images = imagesUrl.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }
            //校验集合是否为空
            if (!CollectionUtils.isEmpty(images)) {
                //将集合转为字符串
                wmNews.setImages(imagesToStr(images));
            }
            //执行修改
            this.updateById(wmNews);
        }
        //替换前缀路径
        if (!CollectionUtils.isEmpty(images)) {
            images = images.stream().map(url -> url.replaceAll(webSite, "")).collect(Collectors.toList());
            //保存关联关系
            saveRelativeInfo(images, wmNews, WemediaConstants.WM_IMAGE_REFERENCE);
        }

    }

    /**
     * 保存素材与文章关联关系的方法
     *
     * @param imagesUrl
     * @param wmNews
     * @param type
     */
    private void saveRelativeInfo(List<String> imagesUrl, WmNews wmNews, Short type) {
        //根据图片路径和id获取相关素材id集合
//        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
//                //跟据userid
//                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
//                //根据图片路径集合
//                .in(WmMaterial::getUrl, imagesUrl)
//                //只查询id
//                .select(WmMaterial::getId));
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(imagesUrl, WmThreadLocalUtils.getUser().getId());
        //检查id数量与关联数量是否一致
        if (ids.size() < imagesUrl.size()) {
            //报异常,素材缺失
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "素材缺失");
        }
        //批量插入关联关系
//        for (WmMaterial wmMaterial : wmMaterials) {
//            WmNewsMaterial material = new WmNewsMaterial();
//            material.setMaterialId(wmMaterial.getId());
//            material.setNewsId(wmNews.getId());
//            material.setType(type);
//            wmNewsMaterialMapper.insert(material);
//        }
        wmNewsMaterialMapper.saveRelations(ids, wmNews.getId(), type);
    }

    /**
     * 提取出内容中，所涉及的素材路径
     *
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {
        //将字符串，转为map集合
        List<Map> mapList = JSON.parseArray(content, Map.class);
        return mapList.stream()//创建流
                //在集合中找到key为image的map
                .filter(mapImage -> "image".equals(mapImage.get("type")))
                //获取map中的value字段
                .map(mapImage -> String.valueOf(mapImage.get("value")))
                //替换路径
                .map(url -> url.replaceAll(webSite, ""))
                //去重
                .distinct()
                //将得到的素材返回里经济和
                .collect(Collectors.toList());
    }

    /**
     * 保存修改文章
     *
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        //2.1.wmNews补全信息（创建时间，上下架，用户id）
        wmNews.setCreatedTime(new Date());
        //默认上架
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        //2.2.判断id是否为空
        if (wmNews.getId() == null) {
            //为空保存wmNews
            this.save(wmNews);
        } else {
            //2.2.1如果不为空，删除素材与文章的关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //修改
            this.updateById(wmNews);
        }
    }

    /**
     * 校验参数
     *
     * @param dto
     * @return
     */
    private WmNews parseDtoToWmNews(WmNewsDTO dto) {
        // 检查内容、标题
        if (StringUtils.isBlank(dto.getTitle()) || StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "文章的标题或内容不能为空");
        }
        //1.1是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "需要登录才能继续操作");
        }
        //1.2.dto拷贝属性wmNews
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //1.3如果type=-1，自动生成，暂时将wmNews设为null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        //1.4images转为字符串
        //判断images集合是否为空
        if (!CollectionUtils.isEmpty(dto.getImages())) {
            //不为空,images转为字符串
            wmNews.setImages(imagesToStr(dto.getImages()));
        }
        //1.5补全id
        wmNews.setUserId(user.getId());
        return wmNews;
    }

    /**
     * images集合转为字符串,用逗号拼接
     *
     * @param images
     * @return
     */
    private String imagesToStr(List<String> images) {
        //创建流对象
        return images.stream()
                //替换(修改，用映射)前缀路径
                .map(url -> url.replaceAll(webSite, ""))
                //拼接字符串，用逗号拼接
                .collect(Collectors.joining(","));
    }
}
